﻿namespace 示例中体现的ModelBus核心思想.ModelBus
{
    /// <summary>
    /// ModelBus协调器：统一管理模型转换和交互
    /// 作为"模型总线"的核心，提供跨模型操作的入口
    /// </summary>
    public class ModelBusCoordinator
    {
        // 存储所有注册的模型转换器
        private readonly Dictionary<(Type Source, Type Target), object> _converters = new();

        /// <summary>
        /// 注册模型转换器
        /// </summary>
        public void RegisterConverter<TSource, TTarget>(IModelConverter<TSource, TTarget> converter)
        {
            var key = (typeof(TSource), typeof(TTarget));
            _converters[key] = converter;
        }

        /// <summary>
        /// 转换模型（通过ModelBus统一调度）
        /// </summary>
        public TTarget Convert<TSource, TTarget>(TSource source)
        {
            var key = (typeof(TSource), typeof(TTarget));
            if (!_converters.TryGetValue(key, out var converter))
            {
                throw new InvalidOperationException($"未找到{typeof(TSource)}到{typeof(TTarget)}的转换器");
            }

            return ((IModelConverter<TSource, TTarget>)converter).Convert(source);
        }

        /// <summary>
        /// 批量转换模型
        /// </summary>
        public IEnumerable<TTarget> Convert<TSource, TTarget>(IEnumerable<TSource> sources)
        {
            var key = (typeof(TSource), typeof(TTarget));
            if (!_converters.TryGetValue(key, out var converter))
            {
                throw new InvalidOperationException($"未找到{typeof(TSource)}到{typeof(TTarget)}的转换器");
            }

            return ((IModelConverter<TSource, TTarget>)converter).Convert(sources);
        }
    }
}
